package mobilesearch.thread;

import android.content.ContentResolver;
import mobilesearch.data.AudioData;
import mobilesearch.ui.BroadcastCommand;

import java.util.ArrayList;
import android.database.Cursor;
import android.provider.MediaStore;
import android.util.Log;
import android.content.Intent;
import android.content.Context;

public class AudioSearchThread extends Thread {
	
	private static final String TAG = "AudioSearchThread";
	private ContentResolver resolver;
	private Context context;

	private String audioId = "no id";
	private String fileName = "no name";
	private String artists = "no artists";
	
	public AudioSearchThread(Context context, ContentResolver resolver) {
		super();
		this.context = context;
		this.resolver = resolver;
	}

	@Override
	public void run() {
		Log.i(TAG, "run()");
		
		super.run();
		ArrayList<AudioData> audioList = new ArrayList<AudioData>();
		
		Cursor cursor = this.resolver.query(MediaStore.Audio.Media.INTERNAL_CONTENT_URI, null, null, null, null);
		try{
			if(cursor.moveToFirst()){
				Log.i(TAG, "INTERNAL_CONTENT_URI");
				this.Search(cursor, audioList);
				Log.i(TAG, "INTERNAL search over");
			}
		}catch(Exception exception){
			Log.i(TAG, exception.toString());
		}

		
		cursor = this.resolver.query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null, null, null, null);
		try{
			if(cursor.moveToFirst()){
				Log.i(TAG, "EXTERNAL_CONTENT_URI");

				this.Search(cursor, audioList);
			}
		}catch(Exception exception){
			Log.i(TAG, exception.toString());
		}
		
		//broadcast the audio data
		if(!audioList.isEmpty()){
			Intent audioIntent = new Intent(BroadcastCommand.SEARCH_AUDIO);
			audioIntent.putParcelableArrayListExtra(BroadcastCommand.SEARCH_AUDIO, audioList);
			this.context.sendBroadcast(audioIntent);	
		}

	}
	
	private void Search(Cursor cursor, ArrayList<AudioData> audioList){
		do{
			AudioData data = new AudioData();
			
			int idIndex = cursor.getColumnIndex(MediaStore.Audio.Media._ID);
			this.audioId = cursor.getString(idIndex);
			data.setAudioId(this.audioId);
			Log.i(TAG, this.audioId);
			
			int fileNameIndex = cursor.getColumnIndex(MediaStore.Audio.Media.DISPLAY_NAME);
			this.fileName = cursor.getString(fileNameIndex);
			data.setFileName(this.fileName);
			Log.i(TAG, this.fileName);
			
			int artistIndex = cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST);
			this.artists = cursor.getString(artistIndex);
			data.setArtists(this.artists);
			Log.i(TAG, this.artists);

			
			audioList.add(data);
			
		}while(cursor.moveToNext());
	}
	
}
